using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Threading;

namespace Lib.Helper
{
    public static class DataGridExtensions
    {
        public static void NextCellToEdit(this DataGrid grid)
        {
            if (grid.SelectedItem != null)
            {
                try
                {
                    grid.Dispatcher.BeginInvoke(() =>
                                                                  {
                                                                      int nextColumnIndex = GetNextAvailableColumnIndex(grid);
                                                                      grid.CurrentColumn = grid.Columns[nextColumnIndex];
                                                                      grid.UpdateLayout();
                                                                      grid.ScrollIntoView(grid.SelectedItem, grid.CurrentColumn);
                                                                      grid.BeginEdit();
                                                                  });
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                
            }
        }

        static int GetNextAvailableColumnIndex(DataGrid grid)
        {
            return grid.GetNextAvailableColumn().DisplayIndex;
        }

        public static DataGridColumn GetNextAvailableColumn(this DataGrid grid)
        {

            int nextColumnIndex = grid.CurrentColumn.DisplayIndex + 1;

            if (nextColumnIndex >= grid.Columns.Count)
            {
                nextColumnIndex = 0;
            }

            while (grid.Columns[nextColumnIndex].IsReadOnly || grid.Columns[nextColumnIndex].Visibility == Visibility.Collapsed)
            {
                if (nextColumnIndex < grid.Columns.Count - 1)
                {
                    nextColumnIndex++;
                }
                else
                {
                    nextColumnIndex = 0;
                }
            }

            return grid.Columns[nextColumnIndex];
        }
        public static bool IsLastCell(this DataGrid grid)
        {

            int currentColumnIndex = grid.CurrentColumn.DisplayIndex;

            if (currentColumnIndex == grid.Columns.Count - 1)
            {
                return true;
            }
            else
            {
                //Check if exists an not readonly cell available
                for (int index = currentColumnIndex + 1; index <= grid.Columns.Count - 1; index++)
                {
                    if (!grid.Columns[index].IsReadOnly)
                    {
                        return false;
                    }
                }
                return true;
            }
        }
        public static bool IsLastRow(this DataGrid grid)
        {
            PagedCollectionView source = new PagedCollectionView(grid.ItemsSource);

            return source == null || (grid.SelectedIndex == source.TotalItemCount - 1 ? true : false);
        }
    }

    public class MyDataGrid : DataGrid
    {

        public MyDataGrid()
        {
            DefaultStyleKey = typeof(DataGrid);
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {

            if (e.Key.Equals(Key.Tab) || e.Key.Equals(Key.Enter))
            {
                e.Handled = true;

                if (CurrentColumn != null)
                {
                    //if (CurrentColumn.Header.ToString().ToLower().Contains("serialnumber")) base.OnKeyDown(e);

                    if (this.IsLastRow() & this.IsLastCell()) // Last Row And Last Cell (End of the grid)
                    {
                        //SelectedIndex = SelectedIndex + 1;
                        this.NextCellToEdit();
                    }
                    else if (this.IsLastCell()) // Last Cell
                    {
                        SelectedIndex = SelectedIndex + 1;
                        this.NextCellToEdit();

                    }
                    else // Normal navigation
                    {
                        this.NextCellToEdit();
                    }

                }else
                {
                    try
                    {
                        this.SelectedIndex = 0;
                        CurrentColumn = this.Columns[1];
                    }
                    catch (Exception ex)
                    {
                        
                    }
                   
                }
            }
            else
            {
                base.OnKeyDown(e);
            }

        }

        //protected override void OnSelectionChanged(SelectionChangedEventArgs e)
        //{
        //    try
        //    {
        //        this.BeginEdit();
        //    }
        //    catch (Exception)
        //    {
              
        //    }
           
        //}

        protected override void OnLoadingRow(DataGridRowEventArgs e)
        {
            SelectedIndex = SelectedIndex + 1;
        }


    }
 
}
